const express = require('express')
const session = require('espress-session')


const app = express()

// session认证需要配合cookie才能实现，跨域场景有局限性


app.use(session({
    secret: 'XXXXX',
    resave: false,
    saveUninitialized: true
}))


// 存session
app.post('api/login', (req, resp) => {
    if (req.body.username !== 'admin' || req.body.password !== '000000') {
        return resp.send({
            status: 1,
            msg: '登陆失败'
        })
    }

    resp.session.user = req.body
    resp.session.isLogin = true

    return resp.send({
        status: 0,
        msg: '登陆成功'
    })
})

// 取session
app.get('api/username', (req, resp) => {
    if (!req.session.isLogin) {
        return resp.send({
            status: 1,
            msg: '未登陆'
        })
    }

    return resp.send({
        status: 0,
        msg: '已登陆',
        username: req.session.user.username
    })
})

// 清空session
app.post('api/logout', (req, resp) => {
    
    req.session.destroy()

    resp.send({
        status: 0,
        msg: '退出登陆成功'

    })
})





app.listen(80, () => {
    console.log('express server running: http://127.0.0.1')

})